/**
 * 
 */
package data;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author grupo22
 *
 */
public class ConnectionManager {
	private static ConnectionManager cm; 
	private Driver dBDriver = null;
	private static Properties dbprops = new Properties();
	 
	private ConnectionManager(){
		try {
		 InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("dbconf.properties"); 
		 dbprops.load(is);
		} catch (Exception e) {
			System.err.println("No se ha encontrado el fichero de propiedades de la BD");
			e.printStackTrace();
		}
		
		try {
            String driverName =  dbprops.getProperty("driverName");
        	dBDriver = (Driver) Class.forName(driverName).newInstance();
            DriverManager.registerDriver(dBDriver);
        } catch (Exception e) {
           System.err.println("Unable to register JDBC Driver");
           e.printStackTrace();
        }
	}
	
	public static synchronized ConnectionManager getInstance(){
		if(cm==null){
			cm=new ConnectionManager();
		}
		return cm;
	}
	
	public Connection checkOut(){
		Connection conn = null;
	    try {
	    	String uri = dbprops.getProperty("dBUri");
        	String user = dbprops.getProperty("username");
        	String passwd  = dbprops.getProperty("password");
            conn = DriverManager.getConnection(uri,user ,passwd);
        } catch (Exception e) {
           System.err.println("Unable to open a new JDBC connection");
           e.printStackTrace();
        }
		return conn;
	}
	
	public void checkIn(Connection conn){
		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	protected void finalize(){
		System.out.println("Llamando a finalize de ConnectionManager");
		try {
			DriverManager.deregisterDriver(dBDriver);
		} catch (SQLException e) {
			System.err.println("Unable to deregister JDBC driver");
			e.printStackTrace();
		}
	}
}
